
package chat.application.client;

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


public class XmlParser {
    
    //method accepts xml string and returns message type
    public String getType(String serverXml) {
      String stringNode = null;
      try {
          
          //below code uses BuilderFactory and document builder to create DOM capability
          DocumentBuilderFactory docBuilderFactory =
              DocumentBuilderFactory.newInstance();
          DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
          
          //inputSource is used to read the xml String
          InputSource inputSource = new InputSource();
          inputSource.setCharacterStream(new StringReader(serverXml));

           //use of DOM to retrieve elements and parse to string
          Document doc = docBuilder.parse(inputSource);
          Element root = doc.getDocumentElement();
          
          stringNode = root.getNodeName();
          
      }
      catch (Exception e) {
          e.printStackTrace();
      }
      return stringNode;
    }
    
    //method accepts xml string and returns filled Message object
    public Message parseMessage(String serverXml, String xmlType)
    {
        String stringNode = null;
      try {
          
          //below code uses BuilderFactory and document builder to create DOM capability
          DocumentBuilderFactory docBuilderFactory =
              DocumentBuilderFactory.newInstance();
          DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
          
          //inputSource is used to read the xml String
          InputSource inputSource = new InputSource();
          inputSource.setCharacterStream(new StringReader(serverXml));

           //use of DOM to retrieve elements and parse to string
          Document doc = docBuilder.parse(inputSource);
          
      }
      catch (Exception e) {
          e.printStackTrace();
      }
      /*
      output :
          Name: John
          Title: Manager
          Name: Sara
          Title: Clerk
      */    
        return null;
    }
    
    public static String getCharacterDataFromElement(Element e) {
      Node child = e.getFirstChild();
      if (child instanceof CharacterData) {
         CharacterData cd = (CharacterData) child;
         return cd.getData();
      }
      return "?";
    }
}
